package cc.mrbird.febs.common.datasource.starter.tenant;

import com.alibaba.ttl.TransmittableThreadLocal;
import lombok.Builder;
import lombok.Data;
import lombok.experimental.UtilityClass;

/**
 * 租户
 *
 * @author luowei Creation time 2020/10/21 9:52
 */
@UtilityClass
public class TenantContextHolder {

    private final ThreadLocal<TenantConfig> THREAD_LOCAL_TENANT = new TransmittableThreadLocal<>();

    /**
     * TTL 设置租户ID<br/>
     * <b>谨慎使用此方法,避免嵌套调用。尽量使用 {@code TenantBroker} </b>
     *
     * @param tenantId
     * @see TenantBroker
     */
    public void setTenantConfig(String tenantId, Boolean flag) {
        TenantConfig tenantConfig = TenantConfig.builder().tenantId(tenantId).tenantFlag(flag).build();
        THREAD_LOCAL_TENANT.set(tenantConfig);
    }

    /**
     * 获取TTL中的租户ID
     *
     * @return
     */
    public String getTenantId() {
        return getTenantConfig().getTenantId();
    }

    /**
     * 获取TTL中的租户Flag
     *
     * @return
     */
    public Boolean getTenantFlag() {
        return getTenantConfig().getTenantFlag();
    }

    /**
     * 获取TTL中的租户ID
     *
     * @return
     */
    public TenantConfig getTenantConfig() {
        TenantConfig tenantConfig = THREAD_LOCAL_TENANT.get();
        if (tenantConfig == null) {
            tenantConfig = TenantConfig.builder().tenantId(null).tenantFlag(true).build();
        }
        return tenantConfig;
    }

    public void clear() {
        THREAD_LOCAL_TENANT.remove();
    }

    @Data
    @Builder
    public static class TenantConfig {

        private String tenantId;

        private Boolean tenantFlag;

    }

}
